package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码
        request.setCharacterEncoding("utf-8");
        //1.接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //获取复选框数据
        String remember = request.getParameter("remember");

        //2.调用service查询
        User user = service.login(username, password);

        //判断是否为null
        if (user != null) {
            //登录成功,跳转到BrandServle

            //判断是否勾选记住我
            if ("1".equals(remember)) {   //字符串的equals判断要把字符串写在前面，防止remember在前的时候为空，会报空指针异常
                //勾选了，发送cookie

                //1.创建Cookie对象
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                //设置Cookie存活时间
                c_username.setMaxAge(60 * 60 * 24 * 7); //一周的存活时间
                c_password.setMaxAge(60  * 5 );//五分钟存活时间
                //2.发送Cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            //将登录成功后的user对象存储到session中，（因为user是用户数据，要用session)
            // （登录成功之后要跳到另外一个servlet，这一次会话的两次请求要共享数据，要把数据存储到对应的session或者cookie中
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            String contextPath = request.getContextPath();  //动态获取虚拟目录
            response.sendRedirect(contextPath + "/selectAllServlet");  //登录的请求和跳转到BrandServlet查询所有的这两次请求没有里面没有数据要共享，所以直接用重定向
        } else {
            //登录失败

            //存储错误信息到request中
            request.setAttribute("login_msg", "用户名或密码错误");

            //跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);//注意路径加斜杠

        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}